package com.gutai.admin.biz.auth;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gutai.admin.common.util.JsonUtil;
import com.gutai.admin.entity.User;

/**
 * 
 * 
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2019年1月28日         la.01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author la.01367604
 * @version 1.0
 */
public class JwtTokenHelper {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenHelper.class);

    private final static String secret = "SLDLKKDS323ssdd@#@@gf";
    private static Key signingKey;
    static {
        signingKey = Keys.hmacShaKeyFor(secret.getBytes());
    }

    public static String createToken(User subject){
        String json = JsonUtil.object2Json(subject);
        // Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        return Jwts.builder().setSubject(json).signWith(signingKey).compact();
    }

    public static User verify(String token) {
        if (StringUtils.isNotEmpty(token)) {
            try {
                String subjectJson = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody().getSubject();
                return JsonUtil.json2Object(subjectJson, User.class);
            } catch (JwtException e) {
                // don't trust the JWT!
                logger.error("verify token error! --{}", e);
            }
        }
        return null;
    }
}
